import {getToken} from './index.js'

const baseUrl = 'http://test.freeterna.com:8080/test/'

function ajax(url, { method = 'POST', data = {}, config = {showError: true}}) {
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			dataType: 'json',
			header: {
				'content-type': 'application/json',
				token: getToken(),
			},
			success(res) {
				if (res.statusCode == 200) {
					const respones = res.data
					if (respones.code == 200) {
						resolve(respones)
					} else {
						reject(respones)
						if (config.showError) {
							uni.showToast({
								icon: 'none',
								title: respones.msg
							})
						}
					}
				} else if (res.statusCode == 401) {
					uni.clearStorageSync()
					uni.navigateTo({
						url: '/pages/login/index?back=true'
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: httpStatus[res.statusCode] || '服务器错误'
					})
				}
			},
			fail(res) {
				console.log(res)
				reject(res)
			}
		})
	})
}

const httpStatus = {
	401: '您没有权限',
	500: '服务器错误',
}

function get(url, params, config) {
	return ajax(url, {method: 'get', data: params, config})
}

function post(url, data, config) {
	return ajax(url, {data, config})
}

export {
	baseUrl,
	ajax,
	get,
	post
}
